<?php
if (!defined("APP_PATH")) {
    define('APP_PATH',__DIR__.'/../application/');
    // 加载框架引导文件
    require  __DIR__.'/../thinkphp/start.php';
}
echo "<pre>";
//每天执行一次
frozen_profit();
function frozen_profit()
{
    $debug = config("app_debug");
    if (php_sapi_name() != 'cli' && !$debug) {
        echo '只能在cli模式下或者开启调试模式运行：' . date('Y-m-d H:i:s') . "\r\n";die;
    }
    \think\Log::info("开始每天释放冻结资产");
    echo '开始执行的时间：'.date('Y-m-d H:i:s')."\r\n";
    $redis = rds();
    $bkey = 'frozen_profit';
    if($debug) delkey($redis,$bkey);
    $op = $redis->set($bkey,1,['NX','EX'=>60]);
    if(!$op){
        echo '请勿频繁操作：'.date('Y-m-d H:i:s')."\r\n";
        goto END;
    }

    $users = \db('user')->alias('u')
        ->field('u.id,u.frozen_sum')
        ->join('user_detail ud', 'u.id = ud.uid')
        ->where(['u.frozen_sum'=>['>',0]])
        ->select();

    $frozen_bi = config("site.frozen_bi");
    if (empty($frozen_bi)) {
        echo '冻结资产比例有误：'.date('Y-m-d H:i:s')."\r\n";
        goto END;
    }
    $update = "";
    $update_credit2 = "";
    $update_frozen = "";
    if ($users) {
        foreach ($users as $k => $v) {
            $profit = $v['frozen_sum'] * $frozen_bi / 100;
            if ($v['frozen_sum'] <= 0.0001) continue;
            $update_credit2 .= " when id = {$v['id']} then credit2 + {$profit}";
            $update_frozen .= " when id = {$v['id']} then frozen_sum - {$profit}";
            echo "==========冻结资产释放 ID:{$v['id']}  释放金额：{$profit}==========="."\r\n";
        }
    } else {
        echo '没有用户可释放冻结资产：'.date('Y-m-d H:i:s')."\r\n";
        goto END;
    }
    if ($update_credit2) {
        $update .= ",credit2 =(case {$update_credit2} else credit2 end)";
    }
    if ($update_frozen) {
        $update .= ",frozen_sum =(case {$update_frozen} else frozen_sum end)";
    }
    $prefix = config('database.prefix');
    if($update) $ret = \db()->execute("UPDATE {$prefix}user SET ".trim($update,','));

    if($ret){
        \think\Log::error("冻结资产释放成功");
    } else {
        \think\Log::error("冻结资产释放失败");
        echo '执行失败：'.date('Y-m-d H:i:s')."\r\n";
    }

    delkey($redis,$bkey);
    END:
    \think\Log::info("结束冻结资产释放");
    echo '结束执行的时间：'.date('Y-m-d H:i:s')."\r\n";
}


